package src.Dao.impl;

import org.junit.Test;
import src.Dao.UserDao;
import src.ORM.Annotation.Insert;
import src.ORM.RowMapper;
import src.ORM.SqlSession;
import src.POJO.User;
import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserDaoImpl implements UserDao {
    //原生jdbc查询语句
    @Override
    public void select() {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            String sql = "select * from `user`";
            Connection connection = DriverManager.getConnection("jdbc:mysql://10.211.55.4:3306/data","root","123456");
            Statement st = connection.createStatement();
            ResultSet set  = st.executeQuery(sql);
            while (set.next()){
               int id = set.getInt(1);
               String name = set.getString(2);
               int age = set.getInt(3);
               System.out.println(new User(id,name,age));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void insert(User user) {

    }


    @Test
    public void TestSelect() {
        RowMapper rowMapper = new RowMapper() {
            @Override
            public <T> T rowMapper(ResultSet set) throws SQLException {
                return (T) new User(set.getInt(1),set.getString(2),set.getInt(3));
            }
        };
        List<User> list =  SqlSession.getInstance().select("select * from `user`",rowMapper);
        for(User user:list){
            System.out.println(user);
        }
    }

    @Test
    public void TestSelectOne()  {
        RowMapper rowMapper = new RowMapper() {
            @Override
            public <T> T rowMapper(ResultSet set) throws SQLException{
                int id = set.getInt(1); //获取ID
                String name =  set.getString(2);//获取用户名
                int age = set.getInt(3);
                User user = new User(id,name,age);
                return (T) user;
            }
        };
        User user  =  SqlSession.getInstance().selectOne("select * from `user` where id = ?",rowMapper,0);
        System.out.println(user);
    }

    @Test
    public void TestSelect2(){
        User user  = (User) SqlSession.getInstance().select2("select * from `user`",User.class).get(1);
        System.out.println(user);
    }

    @Test
    public void testInsert() throws Exception {
        String sql = "insert user values (#{id},#{name},#{age})";
        User user = new User(1012,"李三3",29);
        Map<String,Object> map = new HashMap<>();
        map.put("id",10086);
        map.put("name","妞妞");
        map.put("age",10);
        if (SqlSession.getInstance().insert(sql,map)){
            System.out.println("insert succeed！");
        }else {
            System.out.println("insert failed！");
        }
    }
}
